/*
 * @lc app=leetcode.cn id=687 lang=cpp
 *
 * [687] 最长同值路径
 */

#include <limits.h>

#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right)
        : val(x), left(left), right(right) {}
};

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
   public:
    int ans = 0;

    int longestUnivaluePath(TreeNode *root) {
        ans = 0;
        dfs(root);
        return ans;
    }

    int dfs(TreeNode* root){
        if(!root)return 0;
        const int l = dfs(root->left), r = dfs(root->right);
        const int lp = (root->left && root->left->val == root->val) ? l : 0;
        const int rp = (root->right && root->right->val == root->val) ? r : 0;
        ans = max(ans, lp + rp);
        return max(lp, rp) + 1;
    }
};
// @lc code=end
